import 'package:gate_cli/utils/intl_view/utils/project_intl.dart';
import 'package:gate_cli/utils/intl_view/utils/smartling_intl.dart';

class ImportCommand {
  /// 导入翻译后的字符串
  static Map<String, dynamic> listTranslatedStrings({required List<String> associatedArbs}) {
    final strings = <String, dynamic>{};

    for (var element in associatedArbs) {
      /// 翻译名称
      final name = element.replaceAll('.arb', '');

      /// 获取翻译后的 arb 文件列表
      final arbs = SmartlingIntl.instance.getTranslatedArbs(name);
      for (var arb in arbs) {
        final locale = arb.locale;
        final translatedArbFile = arb;

        /// 获取项目对应语言的 arb 文件
        final projectArbFile = ProjectIntl.instance.getArb(locale);

        /// 比较差异
        final diff = translatedArbFile.difference(projectArbFile);
        if (diff.isEmpty) {
          continue;
        }

        /// 合并差异
        final map = strings[locale] as Map<String, dynamic>? ?? {};
        map.addAll(diff);
        strings[locale] = map;
      }
    }
    return strings;
  }

  static void importTranslatedStrings({required List<String> associatedArbs}) {
    final translatedStrings = listTranslatedStrings(associatedArbs: associatedArbs);
    for (var element in translatedStrings.entries) {
      final locale = element.key;
      final map = element.value as Map<String, dynamic>;

      final newStrings = map['new'] as Map<String, String>? ?? {};
      final modifiedStrings = map['modified'] as Map<String, dynamic>? ?? {};
      final strings = <String, String>{};
      for (var element in newStrings.entries) {
        strings[element.key] = element.value;
      }
      for (var element in modifiedStrings.entries) {
        strings[element.key] = element.value['new']!;
      }

      ProjectIntl.instance.getArb(locale).saveAll(strings);
    }
  }
}
